﻿using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

/// <summary>
///ImageGriphics 的摘要说明
/// </summary>
/// 
namespace QzEbook.Common
{
    public class ImageGriphics
    {
        private int width;
        private int height;

        private int newWidth;
        private int newHeight;

        private Size inputSize;
        private int targetWidth = 100;
        private int targetHeight = 100;

        private Image inputImage;
        private ImageFormat format;

        public ImageFormat Format
        {
            get { return format; }
            set { format = value; }
        }
        

        /// <summary>
        /// 传入图像;
        /// </summary>
        public Image InputImage
        {
            get { return inputImage; }
            set
            {
                inputImage = value;
                width =newWidth= inputImage.Width;
                height =newHeight= inputImage.Height;
            }
        }

        /// <summary>
        /// 设置输出图像大小;
        /// </summary>
        public Size OutputSize
        {
            set
            {
                inputSize = value;
                //不允许它太小
                if (inputSize.Width == 0) inputSize.Width = this.width;
                if (inputSize.Height == 0) inputSize.Height = this.height;

                if (this.width > inputSize.Width)
                {
                    targetWidth = inputSize.Width;
                }
                else
                {
                    targetWidth = this.width;
                }
                if (this.height > inputSize.Height)
                {
                    targetHeight = inputSize.Height;
                }
                else
                {
                    targetHeight = this.height; 
                }
                
            }
            get
            {
                return new Size(targetWidth, targetHeight);
            }
        }

        /// <summary>
        /// 以图像创建;
        /// </summary>
        /// <param name="image"></param>
        public ImageGriphics(Image image)
        {
            this.InputImage = image;
            this.Format = image.RawFormat;
        }

        /// <summary>
        /// 以路径创建;
        /// </summary>
        /// <param name="path"></param>
        public ImageGriphics(string path)
        {
            this.InputImage = Image.FromFile(path);
        }

        /// <summary>
        /// 以流创建;
        /// </summary>
        /// <param name="stream"></param>
        public ImageGriphics(Stream stream)
        {
            this.InputImage = Image.FromStream(stream);
        }

        /// <summary>
        /// 重设生成图大小
        /// </summary>
        private void ReDimCutSize()
        {
           float target_ratio = (float)targetWidth / (float)targetHeight;
           float image_ratio = (float)width / (float)height;
            newWidth = targetWidth;
            newHeight = (int)Math.Floor(targetWidth / image_ratio);

            if (newHeight < targetHeight)
            {
                newHeight = targetHeight;
                newWidth = (int)Math.Floor(image_ratio * (float)targetHeight);
            }
        }
        private void ReDimNoCutSize()
        {
            float target_ratio = (float)targetWidth / (float)targetHeight;
            float image_ratio = (float)width / (float)height;

            if (target_ratio > image_ratio)
            {
                newHeight = targetHeight;
                newWidth = (int)Math.Floor(image_ratio * (float)targetHeight);
            }
            else
            {
                newHeight = (int)Math.Floor((float)targetWidth / image_ratio);
                newWidth = targetWidth;
            }
        }

        /// <summary>
        /// 取得等比缩略图,并行行截取;
        /// </summary>
        /// <returns></returns>
        public Image GetThumb()
        {
            this.ReDimCutSize();
            Bitmap bitmap = new Bitmap(inputSize.Width,inputSize.Height);
            Graphics g = Graphics.FromImage(bitmap);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.CompositingMode = CompositingMode.SourceCopy;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(InputImage, new Rectangle(0, 0 ,newWidth,newHeight), 0, 0, InputImage.Width, InputImage.Height, GraphicsUnit.Pixel);
            inputImage.Dispose();
            g.Dispose();
            return bitmap;
          
        }

        /// <summary>
        /// 取得没被截取和图像,但已进行等比缩放;
        /// </summary>
        /// <returns></returns>
        public Image GetNoCatThumb()
        {
            ReDimNoCutSize();
            Bitmap bitmap = new Bitmap(newWidth,newHeight);
            Graphics g = Graphics.FromImage(bitmap);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.CompositingMode = CompositingMode.SourceCopy;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(InputImage, new Rectangle(0, 0, newWidth, newHeight), 0, 0, InputImage.Width, InputImage.Height, GraphicsUnit.Pixel);
            inputImage.Dispose();
            g.Dispose();
            return bitmap;
        }

        /// <summary>
        /// 取得图像类型;
        /// </summary>
        /// <param name="strContentType"></param>
        /// <returns></returns>
        private System.Drawing.Imaging.ImageFormat GetImageType(object strContentType)
        {
            if ((strContentType.ToString().ToLower()) == "image/pjpeg")
            {
                return System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            else if ((strContentType.ToString().ToLower()) == "image/gif")
            {
                return System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if ((strContentType.ToString().ToLower()) == "image/bmp")
            {
                return System.Drawing.Imaging.ImageFormat.Bmp;
            }
            else if ((strContentType.ToString().ToLower()) == "image/tiff")
            {
                return System.Drawing.Imaging.ImageFormat.Tiff;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-icon")
            {
                return System.Drawing.Imaging.ImageFormat.Icon;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-png")
            {
                return System.Drawing.Imaging.ImageFormat.Png;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-emf")
            {
                return System.Drawing.Imaging.ImageFormat.Emf;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-exif")
            {
                return System.Drawing.Imaging.ImageFormat.Exif;
            }
            else if ((strContentType.ToString().ToLower()) == "image/x-wmf")
            {
                return System.Drawing.Imaging.ImageFormat.Wmf;
            }
            else
            {
                return System.Drawing.Imaging.ImageFormat.MemoryBmp;
            }
        }


        /// <summary>
        /// 取得缩略图,并保存
        /// </summary>
        /// <param name="savePath">保存地址</param>
        public void GetThumbAndSave(string savePath)
        {
            Image image = GetThumb();

            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                    break;
                }
            }

            if (jpegICI != null)
            {
                image.Save(savePath, jpegICI, encoderParams);
            }
            else
            {
                image.Save(savePath,Format);
            }
            image.Dispose();

        }


        public static Image CopyRight(Image image)
        {
            Graphics g = Graphics.FromImage(image);

            
            
            g.CompositingQuality = CompositingQuality.HighQuality;
            //g.CompositingMode = CompositingMode.SourceCopy;
           // g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            
            if (Config.CopyRight.ToLower().EndsWith(".jpg")||Config.CopyRight.ToLower().EndsWith(".gif")||Config.CopyRight.ToLower().EndsWith(".png"))
            {
                string copyrightPath = System.Web.HttpContext.Current.Request.MapPath(Config.CopyRight);
                Image copyImage = Image.FromFile(copyrightPath);
                Point p=new Point(image.Width - copyImage.Width, image.Height - copyImage.Height);
                g.DrawImage(copyImage,p);
                copyImage.Dispose();
            }
            else
            {
                Font font = new Font("Tahoma", 12,FontStyle.Bold);
                Brush brush = new SolidBrush(Color.DarkGray);
                SizeF size=g.MeasureString(Config.CopyRight,font);
                Size pad = new Size(10, 10);
                PointF p = new PointF(image.Width-size.Width-pad.Width, image.Height - size.Height-pad.Height);
                g.DrawString(Config.CopyRight, font, brush, p);
            }
            
            g.Dispose();

            return image;
        }


        public static Image CopyRightAndSave(Image original_image, string savePath)
        {
            ImageFormat format = original_image.RawFormat;
            Image image = CopyRight(original_image);

            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                    break;
                }
            }

            if (jpegICI != null)
            {
                image.Save(savePath, jpegICI, encoderParams);
            }
            else
            {
                image.Save(savePath, format);
            }
            //image.Dispose();
            //因为还要进行缩略图的生成;
            return image;
        }
    }
}
